package com.lezhu.plcsdklibrary;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.bjw.bean.ComBean;
import com.bjw.utils.FuncUtil;
import com.bjw.utils.SerialHelper;
import com.lezhu.plcsdklibrary.callback.CmdListener;
import com.lezhu.plcsdklibrary.callback.DoorAllOpenStatusInterface;
import com.lezhu.plcsdklibrary.callback.DoorListener;
import com.lezhu.plcsdklibrary.callback.DoorStatusInterface;
import com.lezhu.plcsdklibrary.callback.HumanApproachListener;
import com.lezhu.plcsdklibrary.callback.OpenDoorListener;
import com.lezhu.plcsdklibrary.manager.DoorCallBackManager;
import com.lezhu.plcsdklibrary.manager.DoorStatusCallBackManager;
import com.lezhu.plcsdklibrary.manager.InfraredSensorCallBackManager;
import com.lezhu.plcsdklibrary.manager.OpenDoorCallBackManager;

import android_serialport_api.SerialPortFinder;

/**
 * 描述：PlcSDK
 * 作者: 钮家齐
 * 时间: 2020/5/28 8:42
 */
public class PlcSDK {
    private static final String TAG = "PlcSDK";

    private static PlcSDK plcSDK;
    private SerialPortFinder serialPortFinder;
    private SerialHelper serialHelper;
    private CmdListener cmdListener;

    public static PlcSDK getInstance() {
        if (plcSDK == null) {
            synchronized (PlcSDK.class) {
                if (plcSDK == null) {
                    plcSDK = new PlcSDK();
                }
            }
        }
        return plcSDK;
    }

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            ComBean comBean = (ComBean) msg.obj;
            if (cmdListener != null) {
                cmdListener.cmd(2, FuncUtil.ByteArrToHex(comBean.bRec));
            }
            //todo 处理下位机返回的命令
            CmdUtil.processResultCmd(FuncUtil.ByteArrToHex(comBean.bRec));
//            if (Commons.isOld) {
//                CmdUtilold.processResultCmd(FuncUtil.ByteArrToHex(comBean.bRec));
//            } else {
//
//            }

        }
    };

    /**
     * 初始化sdk
     */
    public boolean init() {
        if (serialHelper != null && serialHelper.isOpen()) {
            //如果 serialHelper  不为空且 串口是打开的返回true
            if (cmdListener != null) {
                cmdListener.cmd(2, "串口正常");
            }
            return true;
        } else {
            serialPortFinder = new SerialPortFinder();
            serialHelper = new SerialHelper() {
                @Override
                protected void onDataReceived(final ComBean comBean) {
                    //接收下位机发过来的命令
                    Message obtain = Message.obtain();
                    obtain.obj = comBean;
                    handler.sendMessage(obtain);
                }
            };
            //todo 设置波特率
            serialHelper.setBaudRate(Constants.BaudRate);
            //todo 设置串口地址
            serialHelper.setPort("/dev/ttyS4");

            try {
                serialHelper.open();
                return true;
            } catch (Exception e) {
                if (cmdListener != null) {
                    cmdListener.cmd(2, "串口打开失败");
                }
                e.printStackTrace();
                return false;
            }
        }

    }


    //关闭串口
    public void close() {
        if (serialHelper != null) {
            serialHelper.close();
        }
    }

    /**
     * 获取串口地址
     *
     * @return
     */
    public String[] getAddress() {
        String[] ports = serialPortFinder.getAllDevicesPath();
        return ports;
    }


    /**
     * 回复指令
     *
     * @param cmd
     */
    public void ReplyCmd(String cmd) {
        if (serialHelper == null) {
            Log.e(TAG, "先初始化plcSdk");
            return;
        }
        if (serialHelper.isOpen()) {
            if (cmdListener != null) {
                cmdListener.cmd(1, cmd);
            }
            Log.i(TAG, "回复指令：" + cmd);
            serialHelper.sendHex(cmd);
            OperatListUtls.getInstance().addLog("回复指令==" + cmd);
        } else {
            Log.e(TAG, "搞毛啊,串口都没打开,指令回复失败");
        }
    }

    /**
     * 开门
     *
     * @param pos 1~60
     */
    public void OpenDoor(int pos) {
        //todo 开门增加防抖处理，
        if (!NoDoubleClickUtils.isCanClick()) {
            Log.e(TAG, "请勿频繁调用");
            return;
        }
        if (serialHelper == null) {
            Log.e(TAG, "先初始化plcSdk");
            if (cmdListener != null) {
                cmdListener.cmd(2, "先初始化plcSdk");
            }
            return;
        }
        if (serialHelper.isOpen()) {
            serialHelper.sendHex(Constants.getCMD(pos));
        } else {
            Log.e(TAG, "串口都没打开,不给开门");
            if (cmdListener != null) {
                cmdListener.cmd(2, "串口都没打开,不给开门");
            }
        }
    }


    /**
     * 读取指定门的状态
     *
     * @param pos 1~60
     */
    public void ReadDoorStatus(int pos, DoorStatusInterface statusInterface) {
        if (serialHelper == null) {
            Log.e(TAG, "先初始化plcSdk");
            return;
        }
        if (serialHelper.isOpen()) {
            DoorCallBackManager.getInstance().addCallBack(pos, statusInterface);
            serialHelper.sendHex(Constants.getIdnexCmd(pos));
        } else {
            Log.e(TAG, "串口都没打开,不让读取");
        }
    }

    /**
     * 获取全部开门的集合
     */
    public void ReadAllDoorList(DoorAllOpenStatusInterface statusInterface) {
        if (serialHelper == null) {
            Log.e(TAG, "先初始化plcSdk");
            return;
        }
        if (serialHelper.isOpen()) {
            DoorCallBackManager.getInstance().setAllOpenStatusInterface(statusInterface);
            serialHelper.sendHex(Constants.getAllcmd());
        } else {
            Log.e(TAG, "串口都没打开,不让读取");
        }
    }

    /**
     * 请求开门
     *
     * @param pos 如果是柜门号就直接传,如果是下标,要+1
     */
    public void requestOpenDoor(int pos, OpenDoorListener openDoorListener) {
        if (!NoDoubleClickUtils.isCanClick()) {
            Log.e(TAG, "请勿频繁调用");
            return;
        }
        if (serialHelper == null) {
            Log.e(TAG, "先初始化plcSdk");
            return;
        } else {
            if (!serialHelper.isOpen()) {
                init();
            }

        }
        if (serialHelper.isOpen()) {
            OpenDoorCallBackManager.getInstance().addDoorListener(pos, openDoorListener);
            String cmd = Constants.getCMD(pos);
            serialHelper.sendHex(cmd);
            OperatListUtls.getInstance().addLog("发送开门指令:" + cmd);
        } else {
            OperatListUtls.getInstance().addLog("串口没有打开");
            Log.e(TAG, "串口都没打开,不让读取");
        }
    }

    public void SdkOpen() {
        if (serialHelper != null && !serialHelper.isOpen()) {
            try {
                serialHelper.open();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            init();
        }
    }


    /**
     * 添加人体传感器回调
     */
    public void addhumanApproachListener(HumanApproachListener sensorInterface) {
        InfraredSensorCallBackManager.getInstance().addhumanApproachListener(sensorInterface);
    }

    /**
     * 移除人体传感器回调
     */
    public void removehumanApproachListener(HumanApproachListener sensorInterface) {
        InfraredSensorCallBackManager.getInstance().removehumanApproachListener(sensorInterface);
    }

    /**
     * 添加柜门状态监听
     */
    public void addDoorListener(DoorListener doorListener) {
        DoorStatusCallBackManager.getInstance().addDoorListener(doorListener);
    }

    /**
     * 移除柜门状态监听
     */
    public void removeDoorListener(DoorListener doorListener) {
        DoorStatusCallBackManager.getInstance().removeDoorListener(doorListener);
    }

    public void addCmdListener(CmdListener cmdListener) {
        this.cmdListener = cmdListener;
    }
}
